import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/record/football/zq_schedule_entity.dart';
import 'dart:math' as math;
import 'package:sports_new/entity/record/points_entity.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/utils.dart';
import '../../../resources/colours.dart';
import '../../../resources/styles.dart';
import '../../../utils/routes.dart';
import '../../../widgets/base/qkd_text.dart';
import 'road_match_sheet.dart';

class RoadMatchItem extends StatelessWidget{
  const RoadMatchItem.soccer({super.key, this.match, required this.inBottom,required this.round}):recordType = 0,isChampion = false;
  const RoadMatchItem.basketball({super.key, this.match, required this.inBottom,required this.round}):recordType = 1,isChampion = false;
  const RoadMatchItem.champion({super.key, this.match, required this.inBottom,required this.round,required this.recordType}):isChampion = true;

  final ScheduleGroup? match;
  final bool inBottom;
  final int round;
  final int recordType;
  final bool isChampion;

  bool? get leftWin{
    if(match?.winTeamId.hasValue == true){
      return match?.leftId == match?.winTeamId;
    }else{
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> list = [
      Flex(
        direction: Axis.horizontal,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(child: team(match?.leftLogo, match?.leftName, isLeft: true)),
          Expanded(child: team(match?.rightLogo, match?.rightName, isLeft: false))
        ],
      ),
      score(),
      promotionLine(),
    ];
    return GestureDetector(
      onTap: (){
        if (match?.schedules?[0].matchId.hasValue == true) {
          Utils.onEvent(
            "data_match_view",
            params: {"match_id": match?.schedules?[0].matchId}
          );
          if((match?.schedules?.length ?? 0) < 2){
            Get.toNamed(
              recordType == 0?Routes.zqMatchDetail:Routes.lqMatchDetail,
              arguments: match?.schedules?[0].matchId
            );
          }else{
            Get.bottomSheet(
              RoadMatchSheet(info: match,recordType: recordType),
              isScrollControlled: true
            );
          }
        }
      },
      child: isChampion?champion():Column(
        children: inBottom?list.reversed.toList():list
      )
    );
  }

  Widget champion() {
    return Stack(
      alignment: AlignmentDirectional.center,
      children: [
        Image.asset(height: 52, Utils.getImgPath("champion_back.png")),
        Positioned.fill(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(
                  child: Container(
                    alignment: Alignment.centerRight,
                    child: QkdText(
                      match?.leftName ?? "待定",
                      fontSize: 12, color: Colours.white,
                      maxLines: 2,
                      textAlign: TextAlign.end,
                    ),
                  ),
                ),
                SizedBox(
                  width: 36 + 10 + 6,
                  child: Stack(
                    alignment: AlignmentDirectional.center,
                    children: [
                      CachedNetworkImage(
                        fit: BoxFit.cover,
                        width: 36,
                        height: 36,
                        placeholder: (context, url) => Styles.placeholderIcon(),
                        errorWidget: (context, url, error) => Image.asset(
                          Utils.getImgPath("${recordType == 0?"zq":"lq"}_placeholder.png")
                        ),
                        imageUrl: match?.leftLogo ?? ''
                      ),
                      if (leftWin == true)
                      Positioned(
                        top: 4,
                        right: 0,
                        child: Image.asset(
                          height: 12, Utils.getImgPath("win_icon.png")
                        )
                      )
                    ],
                  ),
                ),
                match?.leftScore != null
                  ? score(20)
                  : Image.asset(
                    width: 44, Utils.getImgPath("trophy_icon.png")
                ),
                SizedBox(
                  width: 36 + 10 + 6,
                  child: Stack(
                    alignment: AlignmentDirectional.center,
                    children: [
                      CachedNetworkImage(
                        fit: BoxFit.cover,
                        width: 36,
                        height: 36,
                        placeholder: (context, url) => Styles.placeholderIcon(),
                        errorWidget: (context, url, error) => Image.asset(
                          Utils.getImgPath("${recordType == 0?"zq":"lq"}_placeholder.png")
                        ),
                        imageUrl: match?.rightLogo ?? ''
                      ),
                      if (leftWin == false)
                      Positioned(
                        top: 4,
                        right: 0,
                        child: Image.asset(
                          height: 12, Utils.getImgPath("win_icon.png")
                        )
                      )
                    ],
                  ),
                ),
                Expanded(
                  child: Container(
                    alignment: Alignment.centerLeft,
                    child: QkdText(
                      match?.rightName ?? "待定",
                      fontSize: 12, color: Colours.white,
                      maxLines: 2,
                      textAlign: TextAlign.start,
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget team(String? logo,String? name,{required bool isLeft}){
    return ShaderMask(
      shaderCallback: (Rect bounds) => LinearGradient(colors: [
        Colours.white.withOpacity(leftWin != (isLeft?false:true)?1:0.7),
        Colours.white.withOpacity(leftWin != (isLeft?false:true)?1:0.7)
      ]).createShader(bounds),
      child: SizedBox(
        height: round == 16?54:null,
        child: Column(
          children: [
            Container(
              clipBehavior: Clip.antiAlias,
              decoration:
              BoxDecoration(borderRadius: BorderRadius.circular(4)),
              child: CachedNetworkImage(
                width: 20,
                height: 20,
                fit: BoxFit.cover,
                placeholder: (context, url) =>
                  Styles.placeholderIcon(),
                errorWidget: (context, url, error) => Image.asset(
                  Utils.getImgPath("${recordType == 0?"zq":"lq"}_placeholder.png")),
                imageUrl: logo ?? ""
              ),
            ),
            Container(height: 4),
            QkdText(match?.name != null && recordType == 0
              ? match!.name! : name ?? "",
              fontSize:(name??"").split('').length > 3 ? 11 : 12,
              maxLines: 2,
              textAlign: TextAlign.center,
            )
          ],
        ),
      ),
    );
  }

  Widget promotionLine() {
    return LayoutBuilder(builder: (context, constraints) {
      return CustomPaint(
        size: Size(constraints.maxWidth/2, 20),
        painter: PromotionLine(
          constraints.maxWidth/2,
          leftWin: leftWin,
          reverse: inBottom
        ),
      );
    });
  }

  Widget score([double? size]) {
    List<Schedules> info = match?.schedules ?? [];
    List<Widget> list = [];
    if(recordType == 0) {
      for (var i = 0; i < info.length; i++) {
        late Widget score;
        switch (info[i].status) {
          case 7:
            score = QkdText(
              '${i%2==0?info[i].leftScoreEnd ?? 0:info[i].rightScoreEnd ?? 0}-${i%2==0?info[i].rightScoreEnd ?? 0:info[i].leftScoreEnd ?? 0}',
              fontSize: size ?? 12,
              color: size != null ? Colours.white : null,
              fontWeight: FontWeight.w600,
            );
            break;
          case 8:
            score = const QkdText("取消");
            break;
          case 9:
            score = const QkdText("中断");
            break;
          case 10:
            score = const QkdText("腰斩");
            break;
          case 11:
            score = const QkdText("延期");
            break;
          case 12:
            score = const QkdText("待定");
            break;
          default:
            score = QkdText(
              info[i].matchTime.noValue?"":DateTime.tryParse("${info[i].matchTime}")?.formatedString("MM/dd"),
              fontSize: size ?? 12,color: Colours.grey66,
            );
        }
        list.add(score);
      }
    }else{
      if(match?.leftScore != null){
        list.add(
          QkdText(
            '${match?.leftScore ?? 0}-${match?.rightScore ?? 0}',
            fontSize: size ?? 12,
            color: size != null ? Colours.white : null,
            fontWeight: FontWeight.w600,
        )
      );
      }else if(info.hasValue){
        list.add(QkdText(
            DateTime.tryParse(info[0].matchTime ?? '')?.formatedString("MM/dd"),
            fontSize: size ?? 12,color: Colours.grey66
        ));
      }
    }
    if (info.length == 1 && recordType == 0) {
      String text = "";
      if (info[0].leftScoreOT != null && info[0].rightScorePK != null) {
        text =
        "加时${info[0].leftScoreOT}-${info[0].rightScoreOT} 点球${info[0].leftScorePK}-${info[0].rightScorePK}";
      } else if (info[0].leftScoreOT != null && info[0].rightScorePK == null) {
        text = "加时${info[0].leftScoreOT}-${info[0].rightScoreOT}";
      } else if (info[0].leftScoreOT == null && info[0].rightScorePK != null) {
        text = "点球${info[0].leftScorePK}-${info[0].rightScorePK}";
      }
      list.add(QkdText(text,
        fontSize: 9,color: size != null ? Colours.white : null
      ));
    }
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: list,
    );
  }
}

class PromotionLine extends CustomPainter {
  final double width;
  final bool reverse;
  final bool? leftWin;
  PromotionLine(this.width, {this.leftWin, this.reverse = false});

  var losePen = Paint()
    ..strokeWidth = 1
    ..style = PaintingStyle.stroke
    ..color = Colours.greyD9
    ..strokeCap = StrokeCap.round
    ..strokeJoin = StrokeJoin.round;

  var winPen = Paint()
    ..strokeWidth = 1
    ..style = PaintingStyle.stroke
    ..color = Colours.main
    ..strokeCap = StrokeCap.round
    ..strokeJoin = StrokeJoin.round;

  @override
  void paint(Canvas canvas, Size size) {
    Path path1 = Path();
    Path path2 = Path();
    path1.lineTo(0, 6);
    path1.arcToPoint(const Offset(1, 7), radius: const Radius.circular(100));
    path1.lineTo(width / 2, 7);
    path2.moveTo(width, 0);
    path2.lineTo(width, 6);
    path2.arcToPoint(Offset(width - 1, 7), radius: const Radius.circular(100));
    path2.lineTo(width / 2, 7);
    if (reverse) {
      canvas.translate(width, 18);
      canvas.rotate(math.pi);
    }
    canvas.drawPath(path1, leftWin == (reverse?false:true) ? winPen : losePen);
    canvas.drawPath(path2, leftWin == (reverse?true:false) ? winPen : losePen);
    canvas.drawLine(Offset(width / 2, 7), Offset(width / 2, 18),
        leftWin != null ? winPen : losePen);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}